﻿Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports HslCommunication
Imports HslCommunication.LogNet
Imports HslCommunication.Profinet.Siemens
Public Class frmJBGWServer

    '接驳工位PLC控件
    Private plc_1_FKS As SiemensS7Net '法兰板空框上料
    Private plc_1_FLB As SiemensS7Net
    Private plc_1_GJB2 As SiemensS7Net
    Private plc_1_GJB3 As SiemensS7Net
    Private plc_2 As SiemensS7Net

    Private plc_car1 As SiemensS7Net
    Private plc_car2 As SiemensS7Net

    Private g_szInitFileName As String    'ini文件

    'PLC的连接状态
    Public plc_1_FKS_Connected As Boolean = False '法兰板空框上料
    Public plc_1_FLB_Connected As Boolean = False
    Public plc_1_GJB3_Connected As Boolean = False
    Public plc_1_GJB2_Connected As Boolean = False
    Public plc_2_Connected As Boolean = False
    Private logfile As ILogNet            'log文件
    Private _Server_Run As Boolean = True

    Private th As Thread
    Private thRGV As Thread

    Dim _ip_1FKS As String
    Dim _ip_1F As String
    Dim _ip_1G3 As String
    Dim _ip_1G2 As String
    Dim _ip_2 As String
    Dim car1IP As String
    Dim car2IP As String

    Dim doorSocket1 As Socket
    Dim doorSocket2 As Socket
    Public Sub New()
        ''加载DLL到exe的事件
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)
        InitializeComponent()
    End Sub
    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub frmJBGWServer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If

        Me.g_szInitFileName = My.Application.Info.DirectoryPath & "\RGV.ini"
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)

        _ip_1FKS = GetIniFile("JBGW", "1FKS", "", Me.g_szInitFileName)
        _ip_1F = GetIniFile("JBGW", "1F", "", Me.g_szInitFileName)
        _ip_1G3 = GetIniFile("JBGW", "1G3", "", Me.g_szInitFileName)
        _ip_1G2 = GetIniFile("JBGW", "1G2", "", Me.g_szInitFileName)
        _ip_2 = GetIniFile("JBGW", "2G", "", Me.g_szInitFileName)
        car1IP = GetIniFile("IP", "CAR1", "", Me.g_szInitFileName)
        car2IP = GetIniFile("IP", "CAR2", "", Me.g_szInitFileName)

        connectDB()
        th = New Thread(AddressOf Read_JBGW_PLC)
        th.Start()

        thRGV = New Thread(AddressOf ReadRGV)
        thRGV.Start()


        th_door_Recive1 = New Thread(AddressOf doorReciveMsg1)
        th_door_Recive1.Start()

        th_door_Recive2 = New Thread(AddressOf doorReciveMsg2)
        th_door_Recive2.Start()


    End Sub
    Public Sub connectDB()
        'イニシャルファイル情報取得

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Dim DoorIsConnected1 As Boolean = False
    Dim DoorIsConnected2 As Boolean = False
    Dim th_door_Recive1 As Thread
    Dim th_door_Recive2 As Thread
    Private Sub connectDoor1()
        Dim doorIp1 As String = GetIniFile("DOOR", "DOOR1", "127.0.0.1", g_szInitFileName)
        Dim doorPort As String = GetIniFile("DOOR", "PORT", "12345", g_szInitFileName)

        Dim remoteEP1 As New IPEndPoint(Net.IPAddress.Parse(doorIp1), Integer.Parse(doorPort))
        doorSocket1 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        Try
            doorSocket1.Connect(remoteEP1)

            DoorIsConnected1 = True
            logfile.WriteInfo("1车间门 连接成功!")
            updateDoorCommStatus("1", 1)
        Catch ex As Exception
            DoorIsConnected1 = False
            updateDoorCommStatus("1", 0)
            logfile.WriteError("1车间门 连接失败：" & ex.Message)
        End Try

    End Sub
    Private Sub connectDoor2()

        Dim doorIp2 As String = GetIniFile("DOOR", "DOOR2", "127.0.0.1", g_szInitFileName)
        Dim doorPort As String = GetIniFile("DOOR", "PORT", "12345", g_szInitFileName)

        Dim remoteEP2 As New IPEndPoint(Net.IPAddress.Parse(doorIp2), Integer.Parse(doorPort))
        doorSocket2 = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Try
            doorSocket2.Connect(remoteEP2)

            DoorIsConnected2 = True
            logfile.WriteInfo("2车间门 连接成功!")
            updateDoorCommStatus("2", 1)
        Catch ex As Exception
            DoorIsConnected2 = False
            updateDoorCommStatus("2", 0)
            logfile.WriteError("2车间门 连接失败：" & ex.Message)
        End Try


    End Sub
    Private Sub EndConnectDoor1()
        DoorIsConnected1 = False
        Try
            doorSocket1.Shutdown(SocketShutdown.Both)
            doorSocket1.Close()


            'If th_door_Recive1.IsAlive Then
            '    th_door_Recive1.Abort()
            'End If
        Catch ex As Exception

        End Try
    End Sub
    Private Sub EndConnectDoor2()
        DoorIsConnected2 = False
        Try
            doorSocket2.Shutdown(SocketShutdown.Both)
            doorSocket2.Close()

            'If th_door_Recive2.IsAlive Then
            '    th_door_Recive2.Abort()
            'End If
        Catch ex As Exception

        End Try
    End Sub
    Dim temNo As Integer = 0
    Public Sub doorReciveMsg1()
        Dim bytes() As Byte = New Byte(1024) {}
        Dim data As String = String.Empty
        Dim skt As Socket = doorSocket1
        Dim isConnect As Boolean
        Dim DoorID As String = "1"
        While _Server_Run
            isConnect = DoorIsConnected1
            Try

                If isConnect = False Then
                    connectDoor1()
                End If
                skt = doorSocket1
                isConnect = DoorIsConnected1
                If isConnect = True Then 'AndAlso skt?.Available = 0 Then
                    Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+OCCH0=?" & vbCrLf)
                    skt.Send(msg)
                End If

                If isConnect = True AndAlso skt?.Available > 0 Then
                    Dim bytesRec As Integer = skt.Receive(bytes)
                    Dim isOpen As Integer = 0
                    Dim isClose As Integer = 0
                    data = Encoding.UTF8.GetString(bytes, 0, bytesRec)

                    Dim _datastr() As String = data.Replace(Environment.NewLine, "@").Split("@")
                    For Each str As String In _datastr

                        Me.Invoke(setDoorInfoCaller, 1, str)
                        '1#门上升到位信号	Bool	DB16.5.1
                        '1#门下降到位信号	Bool	DB16.5.3
                        If str.Contains("+OCCH1") Then '开门信号

                            Dim strA As String = str.Replace("+OCCH1:", "")
                            If strA = "1" Then
                                updateDoorStatusOpen(DoorID, 1) '打开了
                                Me.Invoke(setDoorStatusCaller, 1, 1)
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.1", True)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.1", True)
                            Else
                                updateDoorStatusOpen(DoorID, 0) '打开或移动中
                                Me.Invoke(setDoorStatusCaller, 1, 0)
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.1", False)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.1", False)
                            End If
                        End If

                        If str.Contains("+OCCH2") Then '关门信号
                            Dim strA As String = str.Replace("+OCCH2:", "")
                            If strA = "1" Then
                                updateDoorStatusClose(DoorID, 1) '关上了
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.3", True)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.3", True)

                            Else
                                updateDoorStatusClose(DoorID, 0) '未关，开或移动中
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.3", False)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.3", False)
                            End If

                        End If

                    Next


                End If

            Catch ex As Exception
                EndConnectDoor1()
            End Try
            Thread.Sleep(1000)
        End While
    End Sub
    Delegate Sub setDoorInfoDEL(doorID As Integer, msg As String)
    Dim setDoorInfoCaller As New setDoorInfoDEL(AddressOf setDoorInfo)
    Dim doorinfoCount As Integer = 0
    Public Sub setDoorInfo(doorID As Integer, msg As String)
        If msg.Trim.Length = 0 Then Exit Sub
        msg = Now.ToString("HH:mm:ss") & "->" & msg
        If doorinfoCount > 500 Then
            txtDoor1.Clear()
            txtDoor2.Clear()
            doorinfoCount = 0
        End If
        If doorID = 1 Then
            txtDoor1.Text = msg.Trim.Replace(vbCr, "") & vbCr & txtDoor1.Text
        Else
            txtDoor2.Text = msg.Trim.Replace(vbCr, "") & vbCr & txtDoor2.Text
        End If
        doorinfoCount = doorinfoCount + 1

    End Sub
    Delegate Sub setDoorStatusDEL(doorID As Integer, msg As Integer)
    Dim setDoorStatusCaller As New setDoorStatusDEL(AddressOf setDoorStatus)
    Public Sub setDoorStatus(doorID As Integer, status As Integer)
        If doorID = 1 Then
            If status = 1 Then
                lblDoor1Status.Text = "开"
                lblDoor1Status.BackColor = Color.GreenYellow
                lblDoor1Status.ForeColor = Color.Black
            Else
                lblDoor1Status.Text = "关"
                lblDoor1Status.BackColor = Color.Red
                lblDoor1Status.ForeColor = Color.White
            End If
        Else
            If status = 1 Then
                lblDoor2Status.Text = "开"
                lblDoor2Status.BackColor = Color.GreenYellow
                lblDoor2Status.ForeColor = Color.Black
            Else
                lblDoor2Status.Text = "关"
                lblDoor2Status.BackColor = Color.Red
                lblDoor2Status.ForeColor = Color.White
            End If
        End If
    End Sub
    Public Sub doorReciveMsg2()
        Dim bytes() As Byte = New Byte(1024) {}
        Dim data As String = String.Empty
        Dim skt As Socket = doorSocket2
        Dim isConnect As Boolean
        Dim DoorID As String = "2"
        While _Server_Run
            isConnect = DoorIsConnected2
            Try
                If isConnect = False Then
                    connectDoor2()
                End If
                skt = doorSocket2
                isConnect = DoorIsConnected2
                If isConnect = True Then 'AndAlso skt?.Available = 0 Then
                    Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+OCCH0=?" & vbCrLf)
                    skt.Send(msg)
                End If

                If isConnect = True AndAlso skt?.Available > 0 Then
                    Dim bytesRec As Integer = skt.Receive(bytes)
                    Dim isOpen As Integer = 0
                    Dim isClose As Integer = 0
                    data = Encoding.UTF8.GetString(bytes, 0, bytesRec)

                    Dim _datastr() As String = data.Replace(Environment.NewLine, "@").Split("@")
                    For Each str As String In _datastr
                        Me.Invoke(setDoorInfoCaller, 2, str)
                        '2#门上升到位信号	Bool	DB16.5.2
                        '2#门下降到位信号	Bool	DB16.5.4

                        If str.Contains("+OCCH1") Then
                            Dim strA As String = str.Replace("+OCCH1:", "")
                            If strA = "1" Then
                                updateDoorStatusOpen(DoorID, 1) '开
                                Me.Invoke(setDoorStatusCaller, 2, 1)
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.2", True)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.2", True)
                            Else
                                updateDoorStatusOpen(DoorID, 0) '开
                                Me.Invoke(setDoorStatusCaller, 2, 0)
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.2", False)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.2", False)

                            End If
                        End If

                        If str.Contains("+OCCH2") Then
                            Dim strA As String = str.Replace("+OCCH2:", "")
                            If strA = "1" Then
                                updateDoorStatusClose(DoorID, 1) ' '关
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.4", True)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.4", True)

                            Else
                                updateDoorStatusClose(DoorID, 0) ' '关
                                If RGV1_CONNECTED Then plc_car1?.Write("DB16.5.4", False)
                                If RGV2_CONNECTED Then plc_car2?.Write("DB16.5.4", False)
                            End If
                        End If

                    Next

                End If

            Catch ex As Exception
                EndConnectDoor2()
            End Try
            Thread.Sleep(1000)
        End While
    End Sub
    Private Sub Read_JBGW_PLC()

        Try
            plc_1_FLB = New SiemensS7Net(SiemensPLCS.S1200)
            With plc_1_FLB
                .IpAddress = _ip_1F
                .Port = 102
                .SetPersistentConnection()

            End With
            plc_1_GJB3 = New SiemensS7Net(SiemensPLCS.S1200)
            With plc_1_GJB3
                .IpAddress = _ip_1G3
                .Port = 102
                .SetPersistentConnection()
            End With
            plc_1_GJB2 = New SiemensS7Net(SiemensPLCS.S1200)
            With plc_1_GJB2
                .IpAddress = _ip_1G2
                .Port = 102
                .SetPersistentConnection()
            End With

            plc_2 = New SiemensS7Net(SiemensPLCS.S1200)
            With plc_2
                .IpAddress = _ip_2
                .Port = 102
                .SetPersistentConnection()
            End With

            plc_1_FKS = New SiemensS7Net(SiemensPLCS.S1200)
            With plc_1_FKS
                .IpAddress = _ip_1FKS
                .Port = 102
                .SetPersistentConnection()
                'If plc_1_FLB_Connected Then Read_1FLB_1GJB3_PLC(plc_1_FLB, dtJBGWName.Rows(_1FKX_ROW), dtJBGWName.Rows(_1FMS_ROW), 11)
            End With

            While _Server_Run
                Try
                    '骨架板2 和 预组装是否一致
                    'GJB_TYPE_IS_EQUALS = Equals_GJB2_YZZ()

                    '验证是否连接成功
                    plc_2_Connected = plc_2.ReadBool("DB200.DBX111.1").IsSuccess()
                    plc_1_GJB2_Connected = plc_1_GJB2.ReadBool("DB15.DBX0.6").IsSuccess()
                    plc_1_GJB3_Connected = plc_1_GJB3.ReadBool("DB1.DBX0.5").IsSuccess()
                    plc_1_FLB_Connected = plc_1_FLB.ReadBool("DB1.DBX0.5").IsSuccess()
                    plc_1_FKS_Connected = plc_1_FKS.ReadInt16("DB30.DBX2.0").IsSuccess

                    If plc_1_FLB_Connected Then
                        Read_1FLB_1GJB3_PLC(plc_1_FLB, "1FKX", "1FMS")
                    Else
                        saveJBGWstatus(setEmptyJBGW("1FKX"))
                        saveJBGWstatus(setEmptyJBGW("1FMS"))
                    End If

                    If plc_1_GJB3_Connected Then
                        'Threading.Thread.Sleep(200)
                        Read_1FLB_1GJB3_PLC(plc_1_GJB3, "1GKX-3", "1GMS-3")
                    Else
                        saveJBGWstatus(setEmptyJBGW("1GKX-3"))
                        saveJBGWstatus(setEmptyJBGW("1GMS-3"))
                    End If

                    If plc_1_GJB2_Connected Then
                        'Threading.Thread.Sleep(200)
                        Read_1GJB2_PLC(plc_1_GJB2)
                    Else
                        saveJBGWstatus(setEmptyJBGW("1GKX-1"))
                        'Threading.Thread.Sleep(200)
                        saveJBGWstatus(setEmptyJBGW("1GMS1-1"))
                        'Threading.Thread.Sleep(200)
                        saveJBGWstatus(setEmptyJBGW("1GMS1-2"))
                    End If

                    If plc_2_Connected Then
                        'Threading.Thread.Sleep(200)
                        Read_2_PLC(plc_2)
                    Else
                        saveJBGWstatus(setEmptyJBGW("2FMX"))
                        saveJBGWstatus(setEmptyJBGW("2FKS"))
                        saveJBGWstatus(setEmptyJBGW("2GMX"))
                        saveJBGWstatus(setEmptyJBGW("2GKS"))
                    End If
                    '法兰板空框上料
                    If plc_1_FKS_Connected Then
                        saveJBGWstatus("1FKS-0", plc_1_FKS.ReadInt16("DB30.DBX2.0").Content)
                    End If

                Catch ex As Exception
                    logfile.WriteError("1:" & ex.Message)
                End Try

                Me.Invoke(setDGVCaller)

                'Thread.Sleep(500)
                'Me.Invoke(setDoorDGVCaller)
            End While

        Catch ex As Exception
            logfile.WriteError("2:" & ex.Message)
        End Try

    End Sub
    Delegate Sub setDGVDet()
    Dim setDGVCaller As New setDGVDet(AddressOf setDGV)
    Private Function setEmptyJBGW(strName As String) As entity_JBGW
        Dim en As New entity_JBGW
        en.gwname = strName
        en.gwcomm = False
        en.carStop = False
        en.gwlksize = 0
        en.gwlknum = 0
        en.gwxl = False
        en.gw1sum = 0
        en.gw2sum = 0
        en.mesplannum = 0
        en.dnflg = False
        en.upflg = False
        en.upflg = False
        en.controlmode = False
        en.total = 0

        Return en
    End Function

    Private Sub Read_1FLB_1GJB3_PLC(_PLC As SiemensS7Net, _kxName As String, _msName As String)
        Dim enKX As New entity_JBGW
        Dim enMS As New entity_JBGW
        Try

            Dim _heard As Boolean = False

            Dim isSuccess As Boolean = _PLC.ReadBool("DB1.DBX0.5").IsSuccess()
            enKX.gwname = _kxName
            enMS.gwname = _msName
            enKX.gwcomm = isSuccess
            enMS.gwcomm = isSuccess
            If isSuccess Then
                enKX.carStop = _PLC.ReadBool("DB1.DBX0.5").Content
                enMS.carStop = _PLC.ReadBool("DB1.DBX0.5").Content

                enKX.gwlksize = _PLC.ReadInt16("DB1.DBW8").Content
                enMS.gwlksize = _PLC.ReadInt16("DB1.DBW8").Content

                enKX.gwlknum = _PLC.ReadInt16("DB1.DBW6").Content
                enMS.gwlknum = _PLC.ReadInt16("DB1.DBW4").Content

                enKX.gwxl = _PLC.ReadBool("DB1.DBX0.3").Content
                enMS.gwxl = "-"

                enMS.gw1sum = _PLC.ReadInt16("DB1.DBW10").Content
                enKX.gw1sum = 0

                enMS.gw2sum = _PLC.ReadInt16("DB1.DBW12").Content
                enKX.gw2sum = 0

                enMS.mesplannum = _PLC.ReadInt16("DB1.DBW14").Content '- _PLC.ReadInt16("DB1.DBW16").Content 'MES要求数 - 上料框总数
                enKX.mesplannum = 0

                enMS.upflg = _PLC.ReadBool("DB1.DBX0.0").Content
                enKX.upflg = False

                enMS.dnflg = False
                enKX.dnflg = _PLC.ReadBool("DB1.DBX0.1").Content

                enMS.total = _PLC.ReadInt16("DB1.DBW16").Content
                enKX.total = _PLC.ReadInt16("DB1.DBW18").Content

                Dim am As Boolean = _PLC.ReadBool("DB1.DBX1.7").Content
                enMS.controlmode = am
                enKX.controlmode = am

                saveJBGWstatus(enMS)
                saveJBGWstatus(enKX)
            End If
            '_drKX.AcceptChanges()
            '_drMS.AcceptChanges()
        Catch ex As Exception
            logfile.WriteError("3:" & ex.Message)
        End Try
    End Sub
    Private Sub Read_1GJB2_PLC(_PLC As SiemensS7Net)
        Dim enKX As New entity_JBGW
        Dim enMS As New entity_JBGW
        Dim enMS2 As New entity_JBGW

        Try
            Dim _heard As Boolean = False
            enKX.gwname = "1GKX-1"
            enMS.gwname = "1GMS1-1"
            enMS2.gwname = "1GMS1-2"

            Dim isSuccess As Boolean = _PLC.ReadBool("DB15.DBX0.6").IsSuccess()
            enKX.gwcomm = isSuccess
            enMS.gwcomm = isSuccess
            enMS2.gwcomm = isSuccess
            If isSuccess Then
                enKX.carStop = _PLC.ReadBool("DB15.DBX0.7").Content
                enMS.carStop = _PLC.ReadBool("DB15.DBX0.7").Content
                enMS2.carStop = _PLC.ReadBool("DB15.DBX0.7").Content

                enKX.gwlksize = _PLC.ReadInt16("DB15.DBW10").Content
                enMS.gwlksize = _PLC.ReadInt16("DB15.DBW10").Content
                enMS2.gwlksize = _PLC.ReadInt16("DB15.DBW10").Content

                If _PLC.ReadInt16("DB15.DBW8").Content = 0 Then
                    enKX.gwlknum = 0
                Else
                    enKX.gwlknum = _PLC.ReadInt16("DB15.DBW8").Content - 1
                End If

                enMS.gwlknum = _PLC.ReadInt16("DB15.DBW4").Content
                enMS2.gwlknum = _PLC.ReadInt16("DB15.DBW6").Content

                enKX.gwxl = _PLC.ReadBool("DB15.DBX0.5").Content
                enMS.gwxl = "-"
                enMS2.gwxl = "-"

                enMS.gw1sum = 0
                enMS2.gw1sum = 0
                enKX.gw1sum = 0

                enMS.gw2sum = 0
                enMS2.gw2sum = 0
                enKX.gw2sum = 0

                enMS.mesplannum = _PLC.ReadInt16("DB15.DBW12").Content '- _PLC.ReadInt16("DB1.DBW14").Content - _PLC.ReadInt16("DB1.DBW18").Content
                enMS2.mesplannum = _PLC.ReadInt16("DB15.DBW12").Content ' - _PLC.ReadInt16("DB1.DBW14").Content - _PLC.ReadInt16("DB1.DBW18").Content
                enKX.mesplannum = 0

                enMS.upflg = _PLC.ReadBool("DB15.DBX0.0").Content
                enMS.dnflg = False

                enMS2.upflg = _PLC.ReadBool("DB15.DBX0.2").Content
                enMS2.dnflg = False

                enKX.upflg = False
                enKX.dnflg = _PLC.ReadBool("DB15.DBX0.4").Content

                enMS.total = _PLC.ReadInt16("DB15.DBW14").Content
                enKX.total = _PLC.ReadInt16("DB15.DBW16").Content
                enMS2.total = _PLC.ReadInt16("DB15.DBW18").Content

                Dim am As Boolean = _PLC.ReadBool("DB15.DBX20.4").Content
                enMS.controlmode = am
                enKX.controlmode = am
                enMS2.controlmode = am

                saveJBGWstatus(enMS)
                saveJBGWstatus(enMS2)
                saveJBGWstatus(enKX)

            End If
            '_drKX.AcceptChanges()
            '_drMS1.AcceptChanges()
            '_drMS2.AcceptChanges()
        Catch ex As Exception
            logfile.WriteError("4:" & ex.Message)
        End Try
    End Sub

    Private Sub Read_2_PLC(_PLC As SiemensS7Net)

        Dim en2FMX As New entity_JBGW
        Dim en2FKS As New entity_JBGW
        Dim en2GMX As New entity_JBGW
        Dim en2GKS As New entity_JBGW
        en2FMX.gwname = "2FMX"
        en2FKS.gwname = "2FKS"
        en2GMX.gwname = "2GMX"
        en2GKS.gwname = "2GKS"


        Try

            Dim _heard As Boolean = False

            Dim isSuccess As Boolean = _PLC.ReadBool("DB200.DBX111.1").IsSuccess()
            en2FMX.gwcomm = isSuccess
            en2FKS.gwcomm = isSuccess
            en2GMX.gwcomm = isSuccess
            en2GKS.gwcomm = isSuccess
            If isSuccess Then
                en2FMX.carStop = _PLC.ReadBool("DB200.DBX111.3").Content
                en2FKS.carStop = _PLC.ReadBool("DB200.DBX111.3").Content
                en2GMX.carStop = _PLC.ReadBool("DB200.DBX111.6").Content
                en2GKS.carStop = _PLC.ReadBool("DB200.DBX111.6").Content

                en2FMX.gwlksize = CInt(_PLC.ReadByte("DB200.DBX78.0").Content)
                en2FKS.gwlksize = CInt(_PLC.ReadByte("DB200.DBX78.0").Content)
                en2GMX.gwlksize = CInt(_PLC.ReadByte("DB200.DBX79.0").Content)
                en2GKS.gwlksize = CInt(_PLC.ReadByte("DB200.DBX79.0").Content)

                en2FMX.gwlknum = CInt(_PLC.ReadByte("DB200.DBX118.0").Content)
                en2FKS.gwlknum = CInt(_PLC.ReadByte("DB200.DBX119.0").Content)
                en2GMX.gwlknum = CInt(_PLC.ReadByte("DB200.DBX114.0").Content)
                en2GKS.gwlknum = CInt(_PLC.ReadByte("DB200.DBX115.0").Content)

                en2FMX.gwxl = _PLC.ReadBool("DB200.DBX111.1").Content
                en2FKS.gwxl = "-"
                en2GMX.gwxl = _PLC.ReadBool("DB200.DBX111.4").Content
                en2GKS.gwxl = "-"

                en2FMX.gw1sum = 0
                en2FKS.gw1sum = 0
                en2GMX.gw1sum = 0
                en2GKS.gw1sum = 0

                en2FMX.gw2sum = 0
                en2FKS.gw2sum = 0
                en2GMX.gw2sum = 0
                en2GKS.gw2sum = 0

                en2FMX.mesplannum = 0
                en2FKS.mesplannum = 0
                en2GMX.mesplannum = 0
                en2GKS.mesplannum = 0

                en2FMX.dnflg = _PLC.ReadBool("DB200.DBX77.0").Content
                en2FMX.upflg = False

                en2FKS.upflg = _PLC.ReadBool("DB200.DBX77.1").Content
                en2FKS.dnflg = False

                en2GMX.dnflg = _PLC.ReadBool("DB200.DBX77.3").Content
                en2GMX.upflg = False

                en2GKS.upflg = _PLC.ReadBool("DB200.DBX77.4").Content
                en2GKS.dnflg = False

                en2FMX.total = 0
                en2FKS.total = 0
                en2GMX.total = 0
                en2GKS.total = 0

                '自动手动
                Dim fam As Boolean = _PLC.ReadBool("DB200.DBX121.0").Content
                Dim gam As Boolean = _PLC.ReadBool("DB200.DBX121.1").Content

                en2FMX.controlmode = fam
                en2FKS.controlmode = fam
                en2GMX.controlmode = gam
                en2GKS.controlmode = gam

                saveJBGWstatus(en2FMX)
                saveJBGWstatus(en2FKS)
                saveJBGWstatus(en2GMX)
                saveJBGWstatus(en2GKS)

            End If
            '_drKX.AcceptChanges()
            '_drMS.AcceptChanges()
        Catch ex As Exception
            logfile.WriteError("5:" & ex.Message)
        End Try
    End Sub

    Private Function saveJBGWstatus(_dr As entity_JBGW)
        Dim szSql As String = ""
        szSql &= " UPDATE sf.b_record_jbgw_status_monitor  "
        szSql &= " SET "
        szSql &= " gwlksize = ? "
        szSql &= " , gwlknum = ? " '工位的料框数
        szSql &= " , gwxl = ? " '料框型号
        szSql &= " , stop = ? "
        szSql &= " , gwcomm = ? "
        szSql &= " , gw1sum = ? "
        szSql &= " , gw2sum = ? "
        szSql &= " , mesplannum = ? "
        szSql &= " , upflg = ? "
        szSql &= " , dnflg = ? "
        szSql &= " , total = ? "
        szSql &= " , controlmode = ? "
        szSql &= " WHERE "
        szSql &= " gwname = ? "
        Try
            Return DBacs.ExecuteUpdateSql(szSql, -1, _dr.gwlksize, _dr.gwlknum, _dr.gwxl, _dr.carStop, _dr.gwcomm, _dr.gw1sum,
                                                  _dr.gw2sum, _dr.mesplannum, IIf(IsDBNull(_dr.upflg), False, _dr.upflg), IIf(IsDBNull(_dr.dnflg), False, _dr.dnflg),
                                                  _dr.total, IIf(IsDBNull(_dr.controlmode), False, _dr.controlmode), _dr.gwname)
        Catch ex As Exception
            Return -1
        End Try

    End Function

    Private Function saveJBGWstatus(_rowName As String, _intTotal As Integer) As Integer
        Dim szSql As String = ""
        szSql &= " UPDATE sf.b_record_jbgw_status_monitor  "
        szSql &= " SET "
        szSql &= "  total = ? "
        szSql &= " WHERE "
        szSql &= " gwname = ? "
        Try
            Return DBacs.ExecuteUpdateSql(szSql, -1, _intTotal, _rowName)
        Catch ex As Exception
            Return -1
        End Try
    End Function
    Private Sub setDGV()
        Dim szSql As String = ""
        Dim dt As DataTable
        szSql = "select * from sf.b_record_jbgw_status_monitor order by sort asc "
        dt = DBacs.ExecuteSql(szSql, -1)
        dgv.DataSource = dt
    End Sub

    'Delegate Sub setDoorDGVDet()
    'Dim setDoorDGVCaller As New setDoorDGVDet(AddressOf setDOORDGV)
    'Private Sub setDoorDGV()
    '    Dim szSql As String = ""
    '    Dim dt As DataTable
    '    szSql = "select * from sf.b_door_info order by doorid asc "
    '    dt = DBacs.ExecuteSql(szSql, -1)
    '    dgvDoor.DataSource = dt
    'End Sub

    Private Sub 关闭ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles 关闭ToolStripMenuItem.Click

        If MessageBox.Show("关闭后，将无法监控接驳工位及RGV的状态。确定要关闭吗？", "关闭", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
            Exit Sub
        End If
        NotifyIcon1.Dispose()
        _Server_Run = False
        Try

            If DoorIsConnected1 AndAlso IsNothing(doorSocket1) = False Then
                EndConnectDoor1()
            End If
            If DoorIsConnected2 AndAlso IsNothing(doorSocket2) = False Then
                EndConnectDoor2()
            End If

            If th.IsAlive Then
                th.Abort()
            End If
        Catch ex As Exception

        End Try
        End
    End Sub

    Private Sub frmJBGWServer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        Me.Hide()
        e.Cancel = True
    End Sub

    '-----------------------------------------RGV---------------------------------------------------
    Delegate Sub setRGVDGVDet()
    Dim setRGVDGVCaller As New setDGVDet(AddressOf setRGVDGV)

    Private Sub setRGVDGV()
        Dim szSql As String = ""
        Dim dt As DataTable
        szSql = "select * from sf.b_record_rgv_status_monitor order by carname "
        dt = DBacs.ExecuteSql(szSql, -1)
        dgvRGV.DataSource = dt
    End Sub

    Private Sub ReadRGV()
        plc_car1 = New SiemensS7Net(SiemensPLCS.S1200)
        With plc_car1

            .IpAddress = car1IP
            .Port = 102
            .SetPersistentConnection()
        End With
        plc_car2 = New SiemensS7Net(SiemensPLCS.S1200)
        With plc_car2

            .IpAddress = car2IP
            .Port = 102
            .SetPersistentConnection()
        End With
        While True
            readCarPLC(plc_car1, "car1")
            readCarPLC(plc_car2, "car2")
            Me.Invoke(setRGVDGVCaller)

        End While
    End Sub
    Public RGV1_CONNECTED As Boolean = False
    Public RGV2_CONNECTED As Boolean = False
    Private Sub readCarPLC(_RGV_PLC As SiemensS7Net, _carName As String)
        Dim _heard As Boolean = False
        Dim en As New entity_RGV

        Dim isSuccess As Boolean
        'Try
        isSuccess = _RGV_PLC.ReadBool("DB17.26.0").IsSuccess()
        If _carName = "car1" Then
            RGV1_CONNECTED = isSuccess
        Else
            RGV2_CONNECTED = isSuccess
        End If

        en.communication = isSuccess '通讯状态
        en.carname = _carName
        If isSuccess Then

            _heard = Not _heard
            _RGV_PLC.Write("DB16.4.3", _heard)                           '心跳

            en.controlmode = _RGV_PLC.ReadBool("DB17.27.5").Content() '控制模式
            en.battery = _RGV_PLC.ReadFloat("DB17.20.0").Content()   '电量
            en.dooropen = _RGV_PLC.ReadBool("DB17.26.2").Content()   '门状态
            en.currentloc = _RGV_PLC.ReadInt32("DB17.4.0").Content() '当前位置
            en.carStop = _RGV_PLC.ReadBool("DB16.4.4").Content()        '急停
            en.movestatus = _RGV_PLC.ReadInt16("DB17.2.0").Content()
            Dim recStr As String = (Convert.ToString(_RGV_PLC.ReadInt32("DB17.8.0").Content, 2)) '滚轮、升降状态
            If recStr <> "" Then
                recStr = recStr.PadLeft(32, "0")
                Dim i As Integer = 2
                Dim array As Integer() = New Integer(16 - 1) {}
                Dim num As Integer = 0
                While i < 34
                    array(num) = recStr.Substring(32 - i, 2)
                    i += 2
                    num += 1
                End While
                '---------------档板---------------------
                If array(0) = 10 Then
                    en._1_2_up = 0
                    en._1_2_dn = 1
                ElseIf array(0) = 1 Then
                    en._1_2_up = 1
                    en._1_2_dn = 0
                End If

                If array(1) = 10 Then
                    en._1_1_up = 0
                    en._1_1_dn = 1
                ElseIf array(1) = 1 Then
                    en._1_1_up = 1
                    en._1_1_dn = 0
                End If

                If array(2) = 10 Then
                    en._2_2_up = 0
                    en._2_2_dn = 1
                ElseIf array(2) = 1 Then
                    en._2_2_up = 1
                    en._2_2_dn = 0
                End If

                If array(3) = 10 Then
                    en._2_1_up = 0
                    en._2_1_dn = 1
                ElseIf array(3) = 1 Then
                    en._2_1_up = 1
                    en._2_1_dn = 0
                End If
                '----------------------------------------

                If array(4) = 10 Or array(4) = 0 Then
                    'UcRGV1.WPnl_1.BackColor = Color.White '无货
                    en.out1 = 0
                Else
                    'UcRGV1.WPnl_1.BackColor = Color.Black '有货
                    en.out1 = 1

                End If

                If array(5) = 10 Or array(5) = 0 Then
                    'UcRGV1.Npnl_1.BackColor = Color.White '无货
                    en.in1 = 0
                Else
                    'UcRGV1.Npnl_1.BackColor = Color.Black '有货
                    en.in1 = 1
                End If

                If array(6) = 10 Or array(6) = 0 Then
                    'UcRGV1.WPnl_2.BackColor = Color.White '无货
                    en.out2 = 0
                Else
                    'UcRGV1.WPnl_2.BackColor = Color.Black '有货
                    en.out2 = 1
                End If

                If array(7) = 10 Or array(7) = 0 Then
                    'UcRGV1.Npnl_2.BackColor = Color.White '无货
                    en.in2 = 0
                Else
                    'UcRGV1.Npnl_2.BackColor = Color.Black '有货
                    en.in2 = 1
                End If

                If array(8) = 10 Then
                    'UcRGV1.Stop_0 = False
                    en.rollerstop1 = 0
                    en.rollerupdn1 = 1
                Else
                    If array(8) = 1 Then
                        'UcRGV1.Stop_0 = False
                        en.rollerstop1 = 0
                        en.rollerupdn1 = -1
                    Else
                        en.rollerstop1 = 0
                        en.rollerupdn1 = 0
                    End If
                End If

                If array(9) = 10 Then
                    'UcRGV1.Stop_1 = False
                    en.rollerstop2 = 0
                    en.rollerupdn2 = 1
                Else
                    If array(9) = 1 Then
                        'UcRGV1.Stop_1 = False
                        en.rollerstop2 = 0
                        en.rollerupdn2 = -1
                    Else
                        en.rollerstop2 = 0
                        en.rollerupdn2 = 0
                    End If
                End If
                If array(10).ToString().PadLeft(2, "0").Substring(1, 1) = "1" Then
                    'Me.UcRGV1.Stop_0 = True '滚轮停
                    en.rollerstop1 = 1

                End If

                If array(10).ToString().PadLeft(2, "0").Substring(0, 1) = "1" Then
                    'Me.UcRGV1.Stop_1 = True '滚轮停
                    en.rollerstop2 = 1

                End If

            End If
            '1车间门=====================================================================================================
            If _RGV_PLC.ReadBool("DB17.26.5").Content() = True And _RGV_PLC.ReadBool("DB17.26.6").Content() = False Then
                en.outdoor1 = 1 '门1 开

                logfile.WriteDebug("★★★1车间门 打开信号★★★")

                If DoorIsConnected1 AndAlso IsNothing(doorSocket1) = False Then
                    If doorIsOpen("1") = False Then
                        Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=1,5" & vbCrLf)

                        Try
                            doorSocket1.Send(msg) 'TODO测试：
                            logfile.WriteInfo("1车间门 打开 - 成功")
                        Catch ex As SocketException
                            If ex.ErrorCode = 10054 Then
                                logfile.WriteError(String.Format("1车间门打开 错误10054：{0}:{1}", ex.ErrorCode, ex.Message))
                                EndConnectDoor1()
                            End If
                            If ex.ErrorCode = 10057 Then
                                logfile.WriteError(String.Format("1车间门打开 错误10057：{0}:{1}", ex.ErrorCode, ex.Message))
                                EndConnectDoor1()
                            End If
                        Catch ex As Exception
                            logfile.WriteError(String.Format("1车间门打开 错误：{0}", ex.Message))
                            EndConnectDoor1()
                        End Try

                    End If
                End If
                'If DoorIsConnected2 AndAlso IsNothing(doorSocket2) = False Then
                '    If doorIsOpen("2") = False Then
                '        Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=1,5" & vbCrLf)

                '        Try
                '            doorSocket2.Send(msg) 'TODO测试：
                '            logfile.WriteInfo("2车间门 打开 - 成功")
                '        Catch ex As SocketException
                '            If ex.ErrorCode = 10054 Then
                '                logfile.WriteError(String.Format("2车间门打开 错误10054：{0}:{1}", ex.ErrorCode, ex.Message))
                '                EndConnectDoor2()
                '            End If
                '            If ex.ErrorCode = 10057 Then
                '                logfile.WriteError(String.Format("2车间门打开 错误10057：{0}:{1}", ex.ErrorCode, ex.Message))
                '                EndConnectDoor2()
                '            End If
                '        Catch ex As Exception
                '            logfile.WriteError(String.Format("2车间门打开 错误：{0}", ex.Message))
                '            EndConnectDoor2()
                '        End Try
                '    End If
                'End If
            ElseIf _RGV_PLC.ReadBool("DB17.26.5").Content() = False And _RGV_PLC.ReadBool("DB17.26.6").Content() = True Then
                logfile.WriteDebug("●●●1车间门 关门信号●●●")
                en.outdoor1 = 0 '门1 关
                ''''暂时不关=======
                ''''If DoorIsConnected1 AndAlso IsNothing(doorSocket1) = False Then
                ''''    If doorIsOpen("1") = True Then


                ''''        Try
                ''''            Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=0" & vbCrLf)
                ''''            '常关-关闭
                ''''            doorSocket1.Send(msg)
                ''''            '关门（点关）
                ''''            'msg = Encoding.UTF8.GetBytes("AT+STACH2=3,1" & vbCrLf)
                ''''            'doorSocket1.Send(msg)

                ''''        Catch ex As SocketException
                ''''            If ex.ErrorCode = 10054 Then
                ''''                logfile.WriteError(String.Format("1车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                ''''                EndConnectDoor1()
                ''''            End If
                ''''            If ex.ErrorCode = 10057 Then
                ''''                logfile.WriteError(String.Format("1车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                ''''                EndConnectDoor1()
                ''''            End If
                ''''        Catch ex As Exception
                ''''            logfile.WriteError(String.Format("1车间门错误：{0}", ex.Message))
                ''''            EndConnectDoor1()
                ''''        End Try

                ''''    End If
                ''''End If

            ElseIf _RGV_PLC.ReadBool("DB17.26.5").Content() = False And _RGV_PLC.ReadBool("DB17.26.6").Content() = False Then
                en.outdoor1 = 2 '门1 false
            End If
            '2车间门============================================================================================================
            If _RGV_PLC.ReadBool("DB17.26.7").Content() = True And _RGV_PLC.ReadBool("DB17.27.0").Content() = False Then
                logfile.WriteDebug("★★★2车间门 开门信号★★★")
                en.outdoor2 = 1 '门2 开
                'If DoorIsConnected1 AndAlso IsNothing(doorSocket1) = False Then
                '    If doorIsOpen("1") = False Then
                '        Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=1,5" & vbCrLf)
                '        Try
                '            doorSocket1.Send(msg) 'TODO测试：
                '        Catch ex As SocketException
                '            If ex.ErrorCode = 10054 Then
                '                logfile.WriteError(String.Format("1车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                '                EndConnectDoor1()
                '            End If
                '            If ex.ErrorCode = 10057 Then
                '                logfile.WriteError(String.Format("1车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                '                EndConnectDoor1()
                '            End If
                '        Catch ex As Exception
                '            logfile.WriteError(String.Format("1车间门错误：{0}", ex.Message))
                '            EndConnectDoor1()
                '        End Try

                '    End If
                'End If
                If DoorIsConnected2 AndAlso IsNothing(doorSocket2) = False Then
                    If doorIsOpen("2") = False Then
                        Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=1,5" & vbCrLf)
                        Try
                            doorSocket2.Send(msg) 'TODO测试：
                        Catch ex As SocketException
                            If ex.ErrorCode = 10054 Then
                                logfile.WriteError(String.Format("2车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                                EndConnectDoor2()
                            End If
                            If ex.ErrorCode = 10057 Then
                                logfile.WriteError(String.Format("2车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                                EndConnectDoor2()
                            End If
                        Catch ex As Exception
                            logfile.WriteError(String.Format("2车间门错误：{0}", ex.Message))
                            EndConnectDoor2()
                        End Try
                    End If
                End If
            ElseIf _RGV_PLC.ReadBool("DB17.26.7").Content() = False And _RGV_PLC.ReadBool("DB17.27.0").Content() = True Then
                logfile.WriteDebug("●●●2车间门 关门信号●●●")
                en.outdoor2 = 0 '门2 关
                ''''暂时不关
                ''''If DoorIsConnected2 AndAlso IsNothing(doorSocket2) = False Then
                ''''    If doorIsOpen("2") = True Then
                ''''        Dim msg As Byte() = Encoding.UTF8.GetBytes("AT+STACH1=0" & vbCrLf)
                ''''        Try
                ''''            doorSocket2.Send(msg)

                ''''            '关门（点关）
                ''''            msg = Encoding.UTF8.GetBytes("AT+STACH2=3,1" & vbCrLf)
                ''''            doorSocket2.Send(msg)

                ''''        Catch ex As SocketException
                ''''            If ex.ErrorCode = 10054 Then
                ''''                logfile.WriteError(String.Format("2车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                ''''                EndConnectDoor2()
                ''''            End If
                ''''            If ex.ErrorCode = 10057 Then
                ''''                logfile.WriteError(String.Format("2车间门错误：{0}:{1}", ex.ErrorCode, ex.Message))
                ''''                EndConnectDoor2()
                ''''            End If
                ''''        Catch ex As Exception
                ''''            logfile.WriteError(String.Format("2车间门错误：{0}", ex.Message))
                ''''            EndConnectDoor2()
                ''''        End Try
                ''''    End If
                ''''End If

            ElseIf _RGV_PLC.ReadBool("DB17.26.7").Content() = False And _RGV_PLC.ReadBool("DB17.27.0").Content() = False Then
                en.outdoor2 = 2 '门2 false
            End If

            '-----------设定RGV的 门的上升、下降到位信号
            'Dim dtDoorStatus As DataTable = getDoorStatus()
            'If dtDoorStatus.Rows.Count > 0 Then
            '    '1门的状态==============================================
            '    dtDoorStatus.DefaultView.RowFilter = "doorid='1'"
            '    If dtDoorStatus.DefaultView.Item(0)("iscomm") = 1 Then

            '        Dim isOpen As Boolean = IIf(dtDoorStatus.DefaultView.Item(0)("isopen") = 0, False, True)
            '        Dim isClose As Boolean = IIf(dtDoorStatus.DefaultView.Item(0)("isclose") = 0, False, True)

            '        _RGV_PLC.Write("DB16.5.1", isOpen)
            '        _RGV_PLC.Write("DB16.5.3", isClose)
            '    End If
            '    '2门的状态==============================================
            '    dtDoorStatus.DefaultView.RowFilter = "doorid='2'"
            '    If dtDoorStatus.DefaultView.Item(0)("iscomm") = 1 Then

            '        Dim isOpen As Boolean = IIf(dtDoorStatus.DefaultView.Item(0)("isopen") = 0, False, True)
            '        Dim isClose As Boolean = IIf(dtDoorStatus.DefaultView.Item(0)("isclose") = 0, False, True)

            '        _RGV_PLC.Write("DB16.5.2", isOpen)
            '        _RGV_PLC.Write("DB16.5.4", isClose)
            '    End If
            'End If

            'en.outdoor1 = 0
            'en.outdoor2 = 0

        Else
            en.battery = 0 '电量
            en.controlmode = False '控制模式
            en.dooropen = False '门状态
            en.currentloc = 15 '当前位置
            en.carStop = False '急停
            en.movestatus = 0
            en._1_2_up = 0
            en._1_2_dn = 0
            en._1_1_up = 0
            en._1_1_dn = 0
            en._2_2_up = 0
            en._2_2_dn = 0
            en._2_1_up = 0
            en._2_1_dn = 0
            en.out1 = 0
            en.in1 = 0
            en.out2 = 0
            en.in2 = 0
            en.rollerstop1 = 0
            en.rollerupdn1 = 0
            en.rollerstop2 = 0
            en.rollerupdn2 = 0
            en.rollerstop1 = 0
            en.rollerstop2 = 0
            en.outdoor1 = 0
            en.outdoor2 = 0


        End If
        saveRGVstatus(en)
        '_dr.AcceptChanges()
        'Catch ex As Exception
        '     ("_dr" & ex.Message)
        'End Try
    End Sub
    Private Function saveRGVstatus(en As entity_RGV)
        Dim szSql As String = ""
        szSql &= " UPDATE sf.b_record_rgv_status_monitor  "
        szSql &= " SET "
        szSql &= "  in1 = ? "
        szSql &= "  , in2 = ? "
        szSql &= "  , out1 = ? "
        szSql &= "  , out2 = ? "
        szSql &= "  , battery = ? "
        szSql &= "  , dooropen = ? "
        szSql &= "  , currentloc = ? "
        szSql &= "  , stop = ? "
        szSql &= "  , communication = ? "
        szSql &= "  , cmd = ? "
        szSql &= "  , outdoor1 = ? "
        szSql &= "  , outdoor2 = ? "
        szSql &= "  , rollerstop1 = ? "
        szSql &= "  , rollerstop2 = ? "
        szSql &= "  , _1_2_up = ? "
        szSql &= "  , _1_2_dn = ? "
        szSql &= "  , _1_1_up = ? "
        szSql &= "  , _1_1_dn = ? "
        szSql &= "  , _2_2_up = ? "
        szSql &= "  , _2_2_dn = ? "
        szSql &= "  , _2_1_up = ? "
        szSql &= "  , _2_1_dn = ? "
        szSql &= "  , rollerupdn1 = ? "
        szSql &= "  , rollerupdn2 = ? "
        szSql &= "  , movestatus = ? "
        szSql &= "  , activestring = ? "
        szSql &= "  , controlmode = ? "
        szSql &= " WHERE "
        szSql &= "  carname = ? "

        Return DBacs.ExecuteUpdateSql(szSql, -1, en.in1, en.in2, en.out1, en.out2, en.battery, IIf(IsDBNull(en.dooropen), False, en.dooropen),
                                      en.currentloc, IIf(IsDBNull(en.carStop), False, en.carStop),
                                      en.communication, DBNULLtoBlank(en.cmd), DBNULLtoBlank(en.outdoor1), en.outdoor2, en.rollerstop1, en.rollerstop2,
                                      en._1_2_up, en._1_2_dn, en._1_1_up, en._1_1_dn, en._2_2_up, en._2_2_dn, en._2_1_up, en._2_1_dn,
                                      en.rollerupdn1, en.rollerupdn2, en.movestatus, DBNULLtoBlank(en.activestring), IIf(IsDBNull(en.controlmode), False, en.controlmode), en.carname)
    End Function
    Private Function updateDoorStatusOpen(_doorID As String, _isStatus As Integer) As Integer
        Dim szSql As String = ""

        szSql &= "  Update sf.b_door_info "
        szSql &= " SET isopen = ?  "
        szSql &= " WHERE doorid = ?  "

        Return DBacs.ExecuteUpdateSql(szSql, -1, _isStatus, _doorID)
    End Function
    Private Function updateDoorStatusClose(_doorID As String, _isStatus As Integer) As Integer
        Dim szSql As String = ""

        szSql &= "  Update sf.b_door_info "
        szSql &= " SET  isclose =?  "
        szSql &= " WHERE doorid = ?  "

        Return DBacs.ExecuteUpdateSql(szSql, -1, _isStatus, _doorID)
    End Function
    Private Function updateDoorCommStatus(_doorID As String, _iscomm As Integer) As Integer
        Dim szSql As String = ""

        szSql &= "  Update sf.b_door_info "
        szSql &= " SET iscomm = ?   "
        szSql &= " WHERE doorid = ?  "

        Return DBacs.ExecuteUpdateSql(szSql, -1, _iscomm, _doorID)
    End Function

    Public Function doorIsOpen(_doorID As String) As Boolean
        Dim isOpen As Boolean = False
        Dim szSql As String = "select * from sf.b_door_info where doorid=?"

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1, _doorID)
        If dt.Rows.Count > 0 Then
            If dt(0)("isopen") = 1 And dt(0)("isclose") = 0 Then
                isOpen = True
            End If
            If dt(0)("isopen") = 0 And dt(0)("isclose") = 1 Then
                isOpen = False
            End If
        End If
        Return isOpen
    End Function
    Public Function getDoorStatus() As DataTable

        Dim szSql As String = "select * from sf.b_door_info"

        Dim dt As DataTable = DBacs.ExecuteSql(szSql, -1)
        If IsNothing(dt) Then
            dt = New DataTable
        End If

        Return dt
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button4.Click, Button3.Click, Button2.Click
        Dim skt As Socket
        If sender.text.ToString.Contains("一车间") Then
            skt = doorSocket1
        Else
            skt = doorSocket2
        End If
        Dim str As String
        If sender.text.ToString.Contains("开") Then
            str = "AT+STACH1=1,5"
        Else
            str = "AT+STACH1=0"
        End If

        Dim msg As Byte() = Encoding.UTF8.GetBytes(str & vbCrLf)
        skt.Send(msg)
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
    End Sub
End Class
Public Class entity_JBGW
    Public gwname As String  ' 工位名称
    Public gwlksize As Integer  ' 大小size
    Public gwlknum As Integer  ' 当前线上料框的数量
    Public gwxl As String  ' 法兰板/骨架板RGV对接线允许下料
    Public carStop As String  ' 急停
    Public gwcomm As String  ' 通讯是否成功
    Public gw1sum As Integer  ' 1FMS前工位法兰板数量
    Public gw2sum As Integer  ' 1FMS后工位法兰板数量
    Public mesplannum As Integer  ' MES计划数量
    Public upflg As Boolean  ' 上料
    Public dnflg As Boolean  ' 下料
    Public total As Integer  ' 累计料框数量
    Public controlmode As Boolean  ' 手动/自动模式
    Public sort As Integer  ' 排序

End Class

Public Class entity_RGV
    Public carname As String ' 车名
    Public communication As String ' 通讯状态
    Public battery As Double ' 电量
    Public controlmode As Boolean ' 控制模式
    Public currentloc As Integer ' 当前位置
    Public carStop As Boolean ' 急停中
    Public in1 As Integer ' 内1
    Public in2 As Integer ' 内2
    Public out1 As Integer ' 外1
    Public out2 As Integer ' 外2
    Public dooropen As Boolean ' 车门
    Public cmd As String '  
    Public outdoor1 As Integer ' 1车间门
    Public outdoor2 As Integer ' 2车间门
    Public rollerstop1 As Integer ' 1#滚轮停
    Public rollerstop2 As Integer ' 2#滚轮停
    Public _1_2_up As Integer ' 1-2档升
    Public _1_2_dn As Integer ' 1-2档降
    Public _1_1_up As Integer ' 1-1档升
    Public _1_1_dn As Integer ' 1-2档降
    Public _2_2_up As Integer ' 2-2档升
    Public _2_2_dn As Integer ' 2-2档降
    Public _2_1_up As Integer ' 2-1档升
    Public _2_1_dn As Integer ' 2-1档降
    Public rollerupdn1 As Integer ' 1#滚轮上下
    Public rollerupdn2 As Integer ' 2#滚轮上下
    Public movestatus As Integer ' 移动状态
    Public activestring As String ' 动作内容

End Class
